# model

# responsible for various actions to upload a chosen file to the available cloud-based storage-services
# perform RAID-1

from google.appengine.ext import webapp

from boto.connection import HTTPRequest
from boto.s3.connection import *
from boto.s3.key import *

from Utilities import *

from controller.BuildStorageInfo import *
from model.octopus.datastore.OctopusCloudDatabaseOpenStack import OctopusCloudDatabaseOpenStack


class FileUploadHandler(webapp.RequestHandler): 
    def post(self):
        __contentType = 'application/octet-stream'
        
        utilities = Utilities()
        
        username = utilities.getUsername()
        userText = utilities.getUserText()
        
        if username:
            urlText = utilities.getUrlTextLogout()
            url = utilities.getLogout(self)
            
#            successRedirect = self.request.get('success_action_redirect')
#            accessKey = self.request.get('AWSAccessKeyId')
#            policy = self.request.get('policy')
#            signature = self.request.get('signature')
            file = self.request.get('file')            
            key = self.request.get('key')        
            acl = self.request.get('acl')
            contentType = self.request.get('content-type')
            
            bucketname = utilities.getBucketname(username)
            
            if file:
                # TODO: 'NOTE'
                # check if the necessary attributes (key-name, acl, content-type) were set respectively chosen
                # if not, do nothing and print a hint-message for the user
                # if it is, than do the procedure below...
    
                # persist the attributes in the local cache-db
#                localDataStorage = OctopusCloudDatabaseCaching(
#                                                               file = file, 
#                                                               keyName = key,
#                                                               acl = acl,
#                                                               contentType = __contentType
#                                                               )
#                localDataStorage.put()
                
                # determine the available credentials
                credentials = utilities.getCredentials(username)
                credentialsAmount = credentials.count()
                results = credentials.fetch(100)
                
                if credentials:
                    for result in results:
                        regionname = result.regionname
                        
                        if regionname == utilities.getAmazonText():
                            amazonStorageConnection = utilities.getStorageServiceConnectionByResult(utilities, username, result)
                            
                            self.uploadFile(utilities, amazonStorageConnection, bucketname, file, key, acl)
                        
                        if regionname == utilities.getGoogleText():
                            googleStorageConnection = utilities.getStorageServiceConnectionByResult(utilities, username, result)
                            
                            self.uploadFile(utilities, googleStorageConnection, bucketname, file, key, acl)
                            
#                        if regionname == utilities.getOpenStackText():
                            # verbinden
                else:
                    keyList = self.getKeyList(utilities, username, bucketname)                
                    
#                    hintText = _('An error occurred - could not get the available credentials')
                    hintText = 'An error occurred - could not get the available credentials'
                    hintColor = 'red'
                    
                    self.callBuilder(userText, username, url, urlText, hintText, hintColor, keyList)
    
                # when the upload is done - redirect to the select-data-view
                self.redirect('/selectdata')
#                self.redirect('/localcaching')
            else:
    
                keyList = self.getKeyList(utilities, username, bucketname)
    
#                hintText = _('No file chosen - please choose a file')
                hintText = 'No file chosen - please choose a file'
                hintColor = 'red'
                
                self.callBuilder(userText, username, url, urlText, hintText, hintColor, keyList)
        else:
            self.redirect('/')

            

    # handle the file-upload..
    def uploadFile(self, utilities, storageConnection, bucketname, file, key, acl):
        utilities.uploadFile(storageConnection, bucketname, file, key, acl)
    
    # loads a list of keys that will be shown in the responsible view (by default: amazon)
    def getKeyList(self, utilities, username, bucketname):
        storageConnection = self.getAmazonStorageConnection(utilities, username)
        
        keyList = []
        keyListAmazon = utilities.getBucketKeyList(self, storageConnection, bucketname, keyList)
        return keyListAmazon
    
        
    # responsible for the amazon-storage-connection
    def getAmazonStorageConnection(self, utilities, username):
        credentials = utilities.getCredentials(username)
        results = credentials.fetch(100)
        
        if credentials:
            for result in results:
                if result.regionname == utilities.getAmazonText():
                    amazonAccessKey = result.accessKey
                    amazonSecretAccessKey = utilities.decodeSecretAccessKey(username, result.secretAccessKey)
                    amazonEndpointURL = utilities.getAmazonURL()
                    
                    amazonStorageConnection = utilities.getS3Connection(amazonAccessKey, amazonSecretAccessKey, amazonEndpointURL)
                    
                    return amazonStorageConnection
        
    # responsible for the call of the get-method of the BuildStorageInfo-Class
    def callBuilder(self, userText, username, url, urlText, hintText, hintColor, keyList):
        
        templateValues = {
                          'userText': userText,
                          'user': username,
                          'urlText': urlText,
                          'url': url,
                          'urlText': urlText,
                          'hintText': hintText,
                          'hintColor': hintColor
                          }
        
        builder = BuildStorageInfo()
        builder.get(self, templateValues, keyList)

            

